package org.linlinjava.litemall.db.service;

import com.alibaba.druid.support.json.JSONUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.linlinjava.litemall.db.domain.LitemallCart;
import org.linlinjava.litemall.db.domain.LitemallCoupon;
import org.linlinjava.litemall.db.domain.LitemallCouponUser;
import org.linlinjava.litemall.db.domain.LitemallGrouponRules;
import org.linlinjava.litemall.db.util.CouponConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class CouponVerifyService {

    @Autowired
    private LitemallCouponUserService couponUserService;
    @Autowired
    private LitemallCouponService couponService;

    /**
     * 检测优惠券是否适合
     *
     * @param userId
     * @param couponId
     * @param checkedGoodsPrice
     * @return
     */
    public LitemallCoupon checkCoupon(Integer userId, Integer couponId, Integer userCouponId, BigDecimal checkedGoodsPrice, List<LitemallCart> checkedGoodsList, LitemallGrouponRules grouponRules) {
        LitemallCoupon coupon = couponService.findById(couponId);
        if (coupon == null) {
            return null;
        }

        LitemallCouponUser couponUser = couponUserService.findById(userCouponId);
        if (couponUser == null) {
            couponUser = couponUserService.queryOne(userId, couponId);
        } else if (!couponId.equals(couponUser.getCouponId())) {
            return null;
        }

        if (couponUser == null) {
            return null;
        }

        // 检查是否超期
        Short timeType = coupon.getTimeType();
        Short days = coupon.getDays();
        LocalDateTime now = LocalDateTime.now();
        if (timeType.equals(CouponConstant.TIME_TYPE_TIME)) {
            if (now.isBefore(coupon.getStartTime()) || now.isAfter(coupon.getEndTime())) {
                return null;
            }
        }
        else if(timeType.equals(CouponConstant.TIME_TYPE_DAYS)) {
            LocalDateTime expired = couponUser.getAddTime().plusDays(days);
            if (now.isAfter(expired)) {
                return null;
            }
        }
        else {
            return null;
        }
        BigDecimal grouponPrice = new BigDecimal(0);
        if (grouponRules != null) {
            grouponPrice = grouponRules.getDiscount();
        }

        // 检测商品是否符合
        // TODO 目前仅支持全平台商品，所以不需要检测
        Short goodType = coupon.getGoodsType();
        if (goodType.equals(CouponConstant.GOODS_TYPE_CATEGORY)|| goodType.equals(CouponConstant.GOODS_TYPE_BANNER) || goodType.equals(CouponConstant.GOODS_TYPE_GOODS)) {
            checkedGoodsPrice=new BigDecimal("0");//如果不是全局优惠券 就计算非全局优惠券得使用条件
            if(goodType.equals(CouponConstant.GOODS_TYPE_GOODS)){//计算限制商品优惠券是否符合条件
                String[] goods=coupon.getGoodsValue().split(",");
                ArrayList<Integer> goodsList=new ArrayList<>();
                for (int i=0;i<goods.length;i++){
                    goodsList.add(Integer.parseInt(goods[i]));
                }
                for (int i=0;i<checkedGoodsList.size();i++){//
                    LitemallCart checkGoods=checkedGoodsList.get(i);
                    Integer goodsId=checkGoods.getGoodsId();
                    if(goodsList.contains(goodsId)){
                        if (grouponRules != null && grouponRules.getGoodsId().equals(checkGoods.getGoodsId())) {
                            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().subtract(grouponPrice).multiply(new BigDecimal(checkGoods.getNumber())));
                        } else {
                            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
                        }
                    }
                }

            }
            if(goodType.equals(CouponConstant.GOODS_TYPE_BANNER)){//计算限制品牌优惠券是否符合条件
                ObjectMapper mapper = new ObjectMapper();
                ArrayList<Integer> banners= new ArrayList<>();
                try {
                    banners = mapper.readValue(coupon.getGoodsValue(),new TypeReference<List<Integer>>(){});
                } catch (IOException e) {
                    e.printStackTrace();
                }
                for (int i=0;i<checkedGoodsList.size();i++){//
                    LitemallCart checkGoods=checkedGoodsList.get(i);
                    Integer bannerId=checkGoods.getBrandId();
                    if(banners.contains(bannerId)){
                        if (grouponRules != null && grouponRules.getGoodsId().equals(checkGoods.getGoodsId())) {
                            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().subtract(grouponPrice).multiply(new BigDecimal(checkGoods.getNumber())));
                        } else {
                            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
                        }
                    }
                }

            }
            if(goodType.equals(CouponConstant.GOODS_TYPE_CATEGORY)){//计算限制品类优惠券是否符合条件
                ObjectMapper mapper = new ObjectMapper();
                ArrayList<Integer> categorys= new ArrayList<>();
                ArrayList<ArrayList<Integer>> categoryList= new ArrayList<>();
                try {
                    categoryList = mapper.readValue(coupon.getGoodsValue(),new TypeReference<List<List<Integer>>>(){});
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //因为数据是这种形式 所以必须进行处理[[1005000],[1005000,1008002],[1005000,1008008],[1005000,1008009],[1005000,1008016]]
                for (int i=0;i<categoryList.size();i++){
                    ArrayList<Integer> items=categoryList.get(i);
                    if(items!=null){
                        for (int j=0;j<items.size();j++){
                            if(!categorys.contains(items.get(j))){
                                categorys.add(items.get(j));
                            }
                        }
                    }
                }
                for (int i=0;i<checkedGoodsList.size();i++){//
                    LitemallCart checkGoods=checkedGoodsList.get(i);
                    Integer categoryId=checkGoods.getCategoryId();
                    if(categorys.contains(categoryId)){
                        if (grouponRules != null && grouponRules.getGoodsId().equals(checkGoods.getGoodsId())) {
                            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().subtract(grouponPrice).multiply(new BigDecimal(checkGoods.getNumber())));
                        } else {
                            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
                        }
                    }
                }

            }
        }

        // 检测订单状态
        Short status = coupon.getStatus();
        if (!status.equals(CouponConstant.STATUS_NORMAL)) {
            return null;
        }
        // 检测是否满足最低消费
        if (checkedGoodsPrice.compareTo(coupon.getMin()) == -1) {
            return null;
        }

        return coupon;
    }

    public static void main(String[] args) {
        String json="[[1005000],[1005000,1008002],[1005000,1008008],[1005000,1008009],[1005000,1008016]]";
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<ArrayList<Integer>> banners= new ArrayList<>();
        try {
            banners = mapper.readValue(json,new TypeReference<List<List<Integer>>>(){});
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(banners);

    }

}